﻿using MD5Hash;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using WMSSystem.YSL.Dto.JWT;
using WMSSystem.YSL.Dto.LoginDto;
using WMSSystem.YSL.Interfance;

namespace WMSSystem.YSL
{
    /// <summary>
    /// 用户登录应用服务实现
    /// </summary>
    public class UserLoginAppService : ApplicationService, IUserLoginAppService
    {
        private readonly IRepository<UserLogin, Guid> _userLoginRepository;
        private readonly IJwtService _jwtService;

        /// <summary>
        /// 构造函数，注入仓储和JWT服务
        /// </summary>
        public UserLoginAppService(
            IRepository<UserLogin, Guid> userLoginRepository,
            IJwtService jwtService)
        {
            _userLoginRepository = userLoginRepository;
            _jwtService = jwtService;
        }

        /// <summary>
        /// 登录方法，支持多种方式，返回详细提示和JWT令牌
        /// </summary>
        public async Task<LoginResultDto> LoginAsync(LoginDto input)
        {
            try
            {
                // 1. 先根据账号查找用户
                var user = await _userLoginRepository.FirstOrDefaultAsync(u =>
                    (!string.IsNullOrEmpty(input.UserName) && u.UserName == input.UserName)
                );

                if (user == null)
                {
                    return new LoginResultDto
                    {
                        StatusCode = 401,
                        Message = "账号不存在"
                    };
                }

                if (user.IsDisabled)
                {
                    return new LoginResultDto
                    {
                        StatusCode = 403,
                        Message = "账号已被禁用"
                    };
                }

                // 2. 验证密码
                var hashedInputPwd = input.Password.GetMD5();
                if (user.Password != hashedInputPwd)
                {
                    return new LoginResultDto
                    {
                        StatusCode = 402,
                        Message = "密码错误"
                    };
                }

                // 3. 登录成功，生成JWT令牌
                var userInfo = new LoginResultDto
                {
                    Id = user.Id,
                    UserName = user.UserName,
                    PhoneNumber = user.PhoneNumber,
                    Email = user.Email,
                    RealName = user.RealName,
                    CreationTime = user.CreationTime,
                    StatusCode = 200,
                    Message = "登录成功"
                };

                // 生成JWT令牌 - 添加详细的异常处理
                try
                {
                    var tokenString = await _jwtService.GenerateTokenAsync(userInfo);
                    
                    // 直接设置令牌字符串
                    userInfo.Token = tokenString;
                }
                catch (Exception tokenEx)
                {
                    Console.WriteLine($"JWT令牌生成失败: {tokenEx.Message}");
                    Console.WriteLine($"异常堆栈: {tokenEx.StackTrace}");
                    return new LoginResultDto
                    {
                        StatusCode = 500,
                        Message = "令牌生成失败，请稍后重试"
                    };
                }

                return userInfo;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"登录过程中发生异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                
                return new LoginResultDto
                {
                    StatusCode = 500,
                    Message = "登录过程中发生错误，请稍后重试"
                };
            }
        }
        /// <summary>
        /// 注册新用户
        /// </summary>
        public async Task<string> RegisterAsync(RegisterDto input)
        {
            try
            {
                var user = new UserLogin
                {
                    UserName = input.UserName,
                    Password = input.Password.GetMD5(),// PasswordHelper.HashPassword(input.Password), // 加密
                    RealName = input.RealName ?? "",
                    PhoneNumber = input.PhoneNumber,
                    Email = input.Email,
                    QQOpenId = input.QQOpenId,
                    WeChatOpenId = input.WeChatOpenId,
                    IsDisabled = false,
                    CreationTime = DateTime.Now
                };
                var res = await _userLoginRepository.InsertAsync(user);
                if (res != null)
                {
                    return "添加成功";
                }
                else
                {
                    return "添加失败";
                }
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.ToString());
                throw;
            }

        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        public async Task<string> UpdateAsync(UpdateUserLoginDto input)
        {
            try
            {
                var user = await _userLoginRepository.GetAsync(input.Id);
                
                // 如果提供了新密码，则进行加密处理
                if (!string.IsNullOrEmpty(input.Password))
                {
                    user.Password = input.GetMD5();// PasswordHelper.HashPassword(input.Password);
                }
                
                if (!string.IsNullOrEmpty(input.RealName))
                    user.RealName = input.RealName;
                if (!string.IsNullOrEmpty(input.PhoneNumber))
                    user.PhoneNumber = input.PhoneNumber;
                if (!string.IsNullOrEmpty(input.Email))
                    user.Email = input.Email;
                if (!string.IsNullOrEmpty(input.QQOpenId))
                    user.QQOpenId = input.QQOpenId;
                if (!string.IsNullOrEmpty(input.WeChatOpenId))
                    user.WeChatOpenId = input.WeChatOpenId;

                var res = await _userLoginRepository.UpdateAsync(user);
                if (res != null)
                {
                    return "修改成功";
                }
                else
                {
                    return "修改失败";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// 禁用或启用用户
        /// </summary>
        public async Task<string> DisableAsync(DisableUserLoginDto input)
        {
            try
            {
                var user = await _userLoginRepository.GetAsync(input.Id);
                user.IsDisabled = input.IsDisabled;
                var res = await _userLoginRepository.UpdateAsync(user);
                if (res != null)
                {
                    return "删除成功";
                }
                else
                {
                    return "删除失败";
                }
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.ToString());
                throw;
            }
        }
     


        /// <summary>
        /// 获取用户列表
        /// </summary>
        public async Task<List<GetUserListOutput>> GetUserListAsync(GetUserListInput input)
        {
            var query = await _userLoginRepository.GetQueryableAsync();

            // 应用过滤条件
            if (!string.IsNullOrEmpty(input.UserName))
            {
                query = query.Where(u => u.UserName.Contains(input.UserName));
            }

            if (!string.IsNullOrEmpty(input.RealName))
            {
                query = query.Where(u => u.RealName.Contains(input.RealName));
            }

            if (!string.IsNullOrEmpty(input.PhoneNumber))
            {
                query = query.Where(u => u.PhoneNumber.Contains(input.PhoneNumber));
            }

            if (!string.IsNullOrEmpty(input.Email))
            {
                query = query.Where(u => u.Email.Contains(input.Email));
            }

            if (input.IsDisabled.HasValue)
            {
                query = query.Where(u => u.IsDisabled == input.IsDisabled.Value);
            }

            if (input.CreationTimeStart.HasValue)
            {
                query = query.Where(u => u.CreationTime >= input.CreationTimeStart.Value);
            }

            if (input.CreationTimeEnd.HasValue)
            {
                query = query.Where(u => u.CreationTime <= input.CreationTimeEnd.Value);
            }

            // 按创建时间降序排序
            var list = query.OrderByDescending(u => u.CreationTime);

            var users = list;

            return users.Select(u => new GetUserListOutput
            {
                Id = u.Id,
                UserName = u.UserName,
                RealName = u.RealName,
                PhoneNumber = u.PhoneNumber,
                Email = u.Email,
                IsDisabled = u.IsDisabled,
                CreationTime = u.CreationTime
            }).ToList();
        }

        /// <summary>
        /// 分页获取用户列表
        /// </summary>
        public async Task<GetUserListPagedOutput> GetUserListPagedAsync(GetUserListPagedInput input)
        {
            var query = await _userLoginRepository.GetQueryableAsync();

            // 应用过滤条件
            if (!string.IsNullOrEmpty(input.UserName))
            {
                query = query.Where(u => u.UserName.Contains(input.UserName));
            }

            if (!string.IsNullOrEmpty(input.RealName))
            {
                query = query.Where(u => u.RealName.Contains(input.RealName));
            }

            if (!string.IsNullOrEmpty(input.PhoneNumber))
            {
                query = query.Where(u => u.PhoneNumber.Contains(input.PhoneNumber));
            }

            if (!string.IsNullOrEmpty(input.Email))
            {
                query = query.Where(u => u.Email.Contains(input.Email));
            }

            if (input.IsDisabled.HasValue)
            {
                query = query.Where(u => u.IsDisabled == input.IsDisabled.Value);
            }

            if (input.CreationTimeStart.HasValue)
            {
                query = query.Where(u => u.CreationTime >= input.CreationTimeStart.Value);
            }

            if (input.CreationTimeEnd.HasValue)
            {
                query = query.Where(u => u.CreationTime <= input.CreationTimeEnd.Value);
            }

            // 获取总记录数
            var totalCount = query.ToList().Count();

            // 应用排序
            var list = query.OrderBy(x => x.CreationTime).Skip((input.PageIndex - 1) * input.PageSize)
                .Take(input.PageSize).ToList();
          

            var items = list.Select(u => new GetUserListOutput
            {
                Id = u.Id,
                UserName = u.UserName,
                RealName = u.RealName,
                PhoneNumber = u.PhoneNumber,
                Email = u.Email,
                IsDisabled = u.IsDisabled,
                CreationTime = u.CreationTime
            }).ToList();

            return new GetUserListPagedOutput
            {
                Items = items,
                TotalCount = totalCount,
                PageIndex = input.PageIndex,
                PageSize = input.PageSize
            };
        }


    }
}
